import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import router from '../router/Router'
import { closeWs } from './WebSocket'

export const service = axios.create({
    withCredentials: true,
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 30000
})

let loading = null

service.interceptors.request.use((request) => {
    const headers = request.headers
    const token = localStorage.getItem('token')
    if (!headers.Authorization) {
        headers.Authorization = token
    }
    if (request.showLoading) {
        loading = ElLoading.service({
            lock: true,
            text: '拼命加载中......',
            background: 'rgba(0, 0, 0, 0.8)',
        })
    }
    return request
}, (error) => {
    if (error.config.showLoading && loading) {
        loading.close()
        ElMessage.error('请求发送失败')
    }
})

service.interceptors.response.use((response) => {
    const { showLoading } = response.config
    if (showLoading && loading) {
        loading.close()
    }
    const {code, data, message} = response.data
    if (code == 401) {
        closeWs()
        localStorage.removeItem("userInfo")
        localStorage.removeItem("token")
        ElMessage.error(message)
        setTimeout(()=>{
            router.push('/login')
        }, 1000)
        loading.close()
    } else  {
        return response.data
    }
}, (error)=>{
    if (error.config.showLoading && loading) {
        loading.close()
    }
})

function request(options) {
    const { showLoading = true } = options
    options.method = options.method || 'get'
    if (options.method.toLowerCase() == 'get') {
        options.params = options.data
    }
    options.showLoading = showLoading
    service.defaults.baseURL = import.meta.env.VITE_APP_BASE_API
    return service(options)
}

export default request
